package com.earl.carnet.web;

import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.earl.carnet.interceptor.StringEscapeEditor;

/**
 * @author 黄祥谦.
 * @date:2016-1-15 上午11:39:19
 * @version :
 */
public abstract class BaseController {

	@RequestMapping(value = "/download/{url}", method = RequestMethod.GET)
	public ResponseEntity<InputStreamResource> downLoad(@PathVariable String url) throws IOException {
		String prefix = "static/download/"; //classPath 的目录前最，约定所有资源放在static下面
		ClassPathResource file = new ClassPathResource(prefix+url +".mp3");
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity.ok().headers(headers).contentLength(file.contentLength())
				.contentType(MediaType.parseMediaType("application/octet-stream"))
				.body(new InputStreamResource(file.getInputStream()));
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false, false));
	}
}
